package wallet

import (
	"bytes"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/sha256"
	"golang.org/x/crypto/ripemd160"
)

var version=byte(0x00)
const AddressCheckLen=4

type Wallet struct{
	PrivateKey ecdsa.PrivateKey
	PublicKey []byte
}

func (w *Wallet)GetAddress()[]byte{
	hash160:=Ripemd160Hash(w.PublicKey)

	pubkey:=append([]byte{version},hash160...)

	otherbytes:=CheckSum(pubkey)

	bytes:=append(pubkey,otherbytes...)

	return Base58Encode(bytes)
}


func NewWallet()*Wallet{
	curve:=elliptic.P521()

	private,err:=ecdsa.GenerateKey(curve,rand.Reader)
	if err!=nil{
		panic(err)
	}

	PublicKey:=append(private.X.Bytes(),private.Y.Bytes()...)

	return &Wallet{*private,PublicKey}
}


func Ripemd160Hash(payload []byte)[]byte{
	sha:=sha256.New()
	sha.Write(payload)
	hash256:=sha.Sum(nil)

	ripemd:=ripemd160.New()
	ripemd.Write(hash256)
	hash160:=ripemd.Sum(nil)

	return hash160
}

func IsValidateAddress(address []byte)bool{
	version_public_checksum:=Base58Decode(address)

	checksum:=version_public_checksum[len(version_public_checksum)-AddressCheckLen:]
	version_public:=version_public_checksum[:len(version_public_checksum)-AddressCheckLen]

	com:=CheckSum(version_public)

	if bytes.Compare(com,checksum)==0{
		return true
	}
	return false
}